<?php

declare(strict_types=1);

namespace app\admin\service\dynamic;

use app\api\lib\SuPengJun;
use app\common\model\circle\CircleFansModel;
use app\common\model\dynamic\DynamicModel;
use app\common\model\user\UserModel;
use Dengje\Pxy\BaseService;

class CircleService extends BaseService
{
    protected $model = null;


    public function __construct()
    {
        $this->model =  new \app\common\model\circle\CircleModel();
    }

    public function list()
    {
        $where = [];
        $status = request()->get('status', 0);
        $id = request()->get('id');
        $name = request()->get('name', '');
        $intro = request()->get('intro', '');
        if ($status) $where[] = ['status', '=', $status];
        if ($id) $where[] = ['id', '=', $id];
        if ($name) $where[] = ['name', 'like', '%' . $name . '%'];
        if ($intro) $where[] = ['intro', 'like', '%' . $intro . '%'];
        $list = $this->model->where($where)->order(['weigh' => 'desc', 'id' => 'desc'])->paginate(request()->get('page_size/d', 10));
        $list->map(function ($v) {
            $v['user_count'] = CircleFansModel::where('circle_id', $v['id'])->count();
            return $v;
        });
        return $list;
    }

    public function detail($id)
    {
        return $this->model->where('id', $id)->find();
    }

    public function create($data)
    {
        return $this->model->create($data);
    }

    public function update($id, $data)
    {
        $data = $this->preExcludeFields($data);
        DynamicModel::where('circle_id', $id)->update(['circle_name' => $data['name'], 'circle_avatar' => $data['avatar']]);
        return $this->model->where('id', $id)->update($data);
    }

    public function delete($id)
    {
        $this->model->where('id', $id)->delete();
        return success('删除成功！');
    }

    public function user($id, $data)
    {
        $ids = CircleFansModel::where('circle_id', $data['id'])->column('user_id');
        if (count($ids) > 0) {
            $idsOrdered = implode(',', $ids);
            $data = UserModel::whereIn('id', $ids)->orderRaw("FIELD(id, $idsOrdered)")
                ->field('id,avatar,name,gender,age,province,city,country,create_time')
                ->paginate(request()->get('page_size/d', 10));
            $data->map(function ($v) {
                $province = $v['province'];
                if (!$province) $province = $v['city'];
                if (!$province) $province = $v['country'];
                $v['ip_str'] = SuPengJun::addsStr($province);
                return $v;
            });
        } else {
            $data['data'] = [];
        }
        return $data;
    }
}
